//
//  ProgressLoadingView.swift
//  rdb-led-banner
//
//  Created by radiobox3 on 2025/4/18.
//

import UIKit

class ProgressLoadingView: UIView {

    var timer: DispatchSourceTimer?
    var completion: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(progressTrackView)
        self.progressTrackView.snp.makeConstraints{
            $0.center.equalToSuperview()
            $0.size.equalTo(CGSize(width: UIDevice.contentWidth(), height: 54))
        }
        self.progressTrackView.layer.addSublayer(progressLayer)
        self.progressTrackView.addSubview(progressLabel)
        self.progressLabel.snp.makeConstraints{
            $0.center.equalToSuperview()
        }
    }
    
    func startLoading(){
        self.timer = DispatchSource.makeTimerSource()
        let repeatRate = 0.01
        let speedMax: CGFloat = CGFloat(repeatRate) / 2
        let speedMin: CGFloat = CGFloat(repeatRate) / 12
        var percent: CGFloat = .zero
        self.timer?.schedule(deadline: .now(), repeating: repeatRate)
        
        self.timer?.setEventHandler(handler: {
            if RdbSubscribeProductRequest.shared.products.isEmpty{
                percent += speedMin
            }else{
                percent += speedMax
            }
            DispatchQueue.main.async{
                if percent > 1{
                    self.finishTimer()
                }else{
                    self.progressLayer.frame.size.width = percent * (UIDevice.contentWidth())
                    self.progressLabel.text = "\(Int(percent * 100))%"
                }
            }
        })
        self.timer?.resume()
    }
    
    func finishTimer(){
        self.timer?.cancel()
        self.timer = nil
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25){
            self.completion?()
        }
    }
    
    private lazy var progressLayer: CAGradientLayer = {
        let gradientLayer = [UIColor("#9F3FFF"), UIColor("#FF12E7")].gradient { gradient in
            gradient.cornerRadius = 27
            gradient.startPoint = CGPoint.zero
            gradient.endPoint = CGPoint(x: 1, y: 0)
            gradient.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: 54))
            return gradient
        }
        return gradientLayer
    }()
    
    private lazy var progressTrackView: UIView = {
        let container = UIView()
        container.layer.cornerRadius = 27
        container.backgroundColor = UIColor("#FFFDE7").withAlphaComponent(0.3)
        return container
    }()
    
    private lazy var progressLabel: UILabel = {
        let progressLabel = UILabel()
        progressLabel.textColor = UIColor.white
        progressLabel.font = UIFont.semibold(14)
        return progressLabel
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
